package org.xin.framework.component;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.xin.common.constant.Constants;
import org.xin.common.config.RedisCache;
import org.xin.framework.config.exception.CloudException;

import java.util.concurrent.TimeUnit;

/**
 * @author ：xin
 * @date ：Created in 2021/10/2
 * @desc <p>  </p>
 * @modified By：$
 * @version: $
 */
@Slf4j
@Component
public class CaptchaComponent {
    /**
     * 验证码有效期（分钟）
     */
    private static final Integer CAPTCHA_EXPIRATION = 2;

    @Autowired
    private RedisCache redisCache;

    public Dict generateCaptcha() {

        // 保存验证码信息
        String uuid = IdUtil.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;

        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 45, 4, 0);

        redisCache.setCacheObject(verifyKey, captcha.getCode(), CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

        return Dict.create().set("uuid", uuid).set("img", Base64.encode(captcha.getImageBytes())).set("code", captcha.getCode());
    }


    public void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            throw new CloudException("验证码无效");
        }
        if (!code.equalsIgnoreCase(captcha)) {
            throw new CloudException("验证码错误");
        }
    }
}
